layui.use(['table', 'common', 'jquery', 'laytpl', 'layer', 'form'], function () {
    var table = layui.table,
        common = layui.common,
        $ = layui.jquery,
        laytpl = layui.laytpl,
        form = layui.form,
        layer = layui.layer;

    //表格
    var tableData = table.render({
        elem: '#data'
        , url: '/system/role/roleList'
        , cols: [[
              {type: 'checkbox'}
            , {field: 'id', width: 80, title: 'ID', sort: true}
            , {field: 'name', width: 120, title: '角色名称'}
            , {field: 'remark', minWidth: 100, title: '描述', sort: true}
            ,{fixed: 'right', title:'操作', width:150, align:'center', toolbar: '#barOperate'}
        ]]
        , page: true
    });

    //自定义验证规则
    form.verify({
        name: function (value) {
            if (value.length < 2) {
                return '角色名称至少得2个字符啊';
            }
        }
    });

    //监听表格复选框选择
    table.on('checkbox(role)', function (obj) {
        console.log(obj)
    });

    table.on('tool(role)', function(obj){
         var data = obj.data; //获得当前行数据
         var layEvent = obj.event; //获得 lay-event 对应的值（也可以是表头的 event 参数对应的值）
         var tr = obj.tr; //获得当前行 tr 的DOM对象
         if(layEvent === 'detail'){ //查看
             //do somehing
         } else if(layEvent === 'del'){ //删除
             layer.confirm('确认删除？', function(index){
                 common.post("/system/role/deleteRole", {ids: data.id}, function (data) {
                     layer.msg("删除成功", {icon: 1, anim: 6, time: 1000}, function () {
                         obj.del();
                         layer.close(index);
                     });
                 });
             });
         } else if(layEvent === 'edit'){ //编辑
             //查询权限资源
             common.post("/system/permission/permissionListAll", {roleId:data.id}, function (res) {
                 var permissionData = {
                     title: "权限资源",
                     checked:true,
                     list: res
                 };
                 var getTpl = permissionTpl.innerHTML
                     , view = document.getElementById('permissionView');
                 laytpl(getTpl).render(permissionData, function (html) {
                     view.innerHTML = html;
                 });
                 layui.form.render('checkbox');
                 var formDom=$("#showForm");
                 //赋值
                 var list=formDom.find("input[type='text'],input[type='hidden'],select,textarea");
                 for(var i=0;i<list.length;i++){
                     var name=list.eq(i).attr("name");
                     for(var o in data){
                         if(o==name){
                             list.eq(i).val(data[o]);
                         }
                     }
                 }
                 formDom.find(".edit-hide").addClass("hide");
                 formDom.find(".save-update-button").attr("lay-filter","update");
                 layer.open({
                     type: 1
                     , title: '角色修改'
                     , area: ['650px', '420px']
                     , shade: [0.3, '#393D49']
                     ,scrollbar: false
                     , content:formDom
                     , zIndex: layer.zIndex
                 });
             });
         }
     });

    $('.operateTable .layui-btn').on('click', function () {
        var type = $(this).data('type');
        active[type] ? active[type].call(this) : '';
    });
    var active = {
        //添加
        addRole: function () { //添加
            //查询权限资源
            common.post("/system/permission/permissionListAll", {}, function (data) {
                var data = {
                    title: "权限资源",
                    checked:false,
                    list: data
                };
                var getTpl = permissionTpl.innerHTML
                    , view = document.getElementById('permissionView');
                laytpl(getTpl).render(data, function (html) {
                    view.innerHTML = html;
                });
                layui.form.render('checkbox');
                var formDom=$("#showForm");
                var list=formDom.find("input[type='text'],select");
                for(var i=0;i<list.length;i++){
                    list.eq(i).val("");
                }
                formDom.find(".edit-hide").addClass("show");
                formDom.find(".save-update-button").attr("lay-filter","add");
                layer.open({
                    type: 1
                    , title: '角色新增'
                    , area: ['550px', '420px']
                    , shade: [0.3, '#393D49']
                    ,scrollbar: false
                    , content: formDom
                    , zIndex: layer.zIndex
                });
            });
        }
        , deleteBatchRole: function () {
            var checkStatus = table.checkStatus('data')
                , data = checkStatus.data;
            var ids = "";
            for (var i = 0; i < data.length; i++) {
                ids += data[i].id;
                if (i < data.length) {
                    ids += ",";
                }
            }
            layer.confirm('确认删除？', {
                btn: ['确认', '取消'] //可以无限个按钮
            }, function (index) {
                layer.close(index);
                common.post("/system/role/deleteRole", {ids: ids}, function (data) {
                    layer.msg("删除成功", {icon: 1, anim: 6, time: 1000}, function () {
                        tableData.reload();
                    });
                });
            }, function (index) {
                layer.close(index);
            });

        }
    };

    //角色新增
    form.on('submit(add)', function (data) {
        debugger
        var field = data.field;
        var ids = [];
        var params = {};
        for (var obj in field) {
            if (obj.indexOf("permissionId") != -1) {
                ids.push(field[obj]);
            } else {
                params[obj] = field[obj];
            }
        }
        params.permissionIds = ids.join(",");
        if(null==params.permissionIds || ""==params.permissionIds){
            layer.msg("权限资源至少勾选一条", {icon: 2, anim: 6, time: 1000});
            return false;
        }
        common.post("/system/role/saveRole", params, function (data) {
            layer.closeAll();
            layer.msg("增加成功", {icon: 6}, function (index) {
                //刷新表格数据
                tableData.reload();
                layer.close(index);
            });
        });
        return false;
    });

    //角色修改
    form.on('submit(update)', function (data) {
        var field = data.field;
        var ids = [];
        var params = {};
        for (var obj in field) {
            if (obj.indexOf("permissionId") != -1) {
                ids.push(field[obj]);
            } else {
                params[obj] = field[obj];
            }
        }
        params.permissionIds = ids.join(",");
        if(null==params.permissionIds || ""==params.permissionIds){
            layer.msg("权限资源至少勾选一条", {icon: 2, anim: 6, time: 1000});
            return false;
        }
        common.post("/system/role/updateRole", params, function (data) {
            layer.closeAll();
            layer.msg("修改成功", {icon: 6}, function (index) {
                //刷新表格数据
                tableData.reload();
                layer.close(index);
            });
        });
        return false;
    });

    //监听权限勾选
    form.on('checkbox(permission)', function(data){
        var checkboxElem=$(data.elem);
        var id=checkboxElem.attr("keyId");
        var pid=checkboxElem.attr("pid");
        var inputList=checkboxElem.siblings("input");
        if("null"==pid || pid==null || pid==''){//当前操作的是父选项
            if(!data.elem.checked){//当前操作取消勾选
                //取消父选框下的所有子选框
                for(var i=0;i<inputList.length;i++){
                    var inputPid=inputList.eq(i).attr("pid");
                    if(id==inputPid){
                        inputList.eq(i).attr("checked",false);
                        inputList.eq(i).next("div.layui-unselect").removeClass("layui-form-checked");
                    }
                }
            }
        }else{
            //子类勾选，父类默认勾选
            if(data.elem.checked) {//当前操作取消勾选
                for(var i=0;i<inputList.length;i++){
                    var inputId=inputList.eq(i).attr("keyId");
                    if(inputId==pid){
                        inputList.eq(i).attr("checked",true);
                        inputList.eq(i).next("div.layui-unselect").addClass("layui-form-checked");
                        break;
                    }
                }
            }
        }
    });

});